package com.amumu.drama.common.modules.category.manager;

import com.amumu.drama.common.modules.category.dao.CategoryCommonDao;
import com.amumu.drama.common.modules.category.dto.CategorySimpleDto;
import com.amumu.drama.mapper.PmsProductCategoryMapper;
import com.amumu.drama.model.PmsProductCategory;
import com.amumu.drama.model.PmsProductCategoryExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sunzhuang
 * @date 2024/5/13 14:26
 * @desc 微丸子-商品分类管理器
 */

@Service
@Slf4j
public class CategoryManager {

    @Autowired
    private CategoryCommonDao categoryCommonDao;

    @Autowired
    private PmsProductCategoryMapper pmsProductCategoryMapper;

    /**
     * 获取商品一级分类
     * @return
     */
    public List<CategorySimpleDto> listProductCategory() {
        List<CategorySimpleDto> result;
        List<CategorySimpleDto> categorySimpleDtoList = categoryCommonDao.listProductCategory();
        List<Long> firstIds = categorySimpleDtoList.stream().map(i -> i.getId()).collect(Collectors.toList());
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andParentIdIn(firstIds);
        List<PmsProductCategory> productCategories = pmsProductCategoryMapper.selectByExample(example);
        Map<Long, List<PmsProductCategory>> groupedByAge = productCategories.stream()
                .collect(Collectors.groupingBy(PmsProductCategory::getParentId));
        result = categorySimpleDtoList.stream().map(i ->{
            i.setSimpleDtos(groupedByAge.get(i.getId()).stream().sorted(Comparator.comparing(PmsProductCategory::getSort)).map(a ->{
                CategorySimpleDto.SecondCategorySimpleDto dto = new CategorySimpleDto.SecondCategorySimpleDto();
                dto.setId(a.getId());
                dto.setName(a.getName());
                return dto;
            }).collect(Collectors.toList()));
            return i;
        }).collect(Collectors.toList());
        return result;
    }



}
